package com.im.partchat.ui.fragment.learn;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.im.partchat.App;
import com.im.partchat.R;
import com.im.partchat.adapter.base.XRecyclerViewAdapter;
import com.im.partchat.adapter.learn.NewTab7FragmentAdapter;
import com.im.partchat.base.BaseFragment;
import com.im.partchat.base.ILoadingType;
import com.im.partchat.bean.learn.Tab7New;
import com.im.partchat.bean.request.RequestBean;
import com.im.partchat.http.service.DownLoadService;
import com.im.partchat.mvp.persenter.GetNewsPersenter;
import com.im.partchat.utils.rxlifecycle.compact.RxLifecycleCompact;
import com.im.partchat.widget.dialog.QRCodeDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import okhttp3.ResponseBody;

/**
 * Created by flyou on 2017/6/30.
 * VersionCode: 1
 * Desc:
 */

public class Tab7Fragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, XRecyclerViewAdapter.OnLoadMoreListener, NewTab7FragmentAdapter.OnQrCodeClickListener, XRecyclerViewAdapter.OnItemLongClickListener {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.reFreshLayout)
    SwipeRefreshLayout reFreshLayout;
    NewTab7FragmentAdapter adapter;
    private GetNewsPersenter getNewsPersenter;
    private int currentPageNo = 1;
    private static boolean isFirst = true;
    private List<Tab7New> tab1NewList = new ArrayList<>();

    @Override
    public void onLoadDataSuccess(Object o, String flag) {

        List<Tab7New> myTab1NewList;
        Gson gson = new Gson();
        String json = gson.toJson(o);
        Type type = new TypeToken<List<Tab7New>>() {
        }.getType();
        myTab1NewList = gson.fromJson(json.toString(), type);
        Log.d(TAG, "onLoadDataSuccess: " + Thread.currentThread().getName());
        if (myTab1NewList != null) {
            if (myTab1NewList.size() == 10) {
                adapter.isLoadMore(true);
            } else {
                adapter.showLoadComplete();
            }
        }

        if (currentPageNo == 1) {
            if (myTab1NewList == null || myTab1NewList.size() == 0) {
                showEmpty();
                return;
            }


            adapter.clear();
            adapter.addAll(myTab1NewList);
        } else {
            if (myTab1NewList == null || myTab1NewList.size() == 0) {
                adapter.showLoadComplete();
                return;
            }
            if (myTab1NewList.size() < 10) {
                adapter.showLoadComplete();
            }
            adapter.addAll(myTab1NewList);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_learn_list;
    }

    @Override
    protected void initData() {
        getNewsPersenter = new GetNewsPersenter(this, this);
        getNewsPersenter.getNewList(RequestBean.COLUMN_GZPT, 1);
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        reFreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        reFreshLayout.setOnRefreshListener(this);

        adapter = new NewTab7FragmentAdapter(App.getApplication(), recyclerView, tab1NewList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(App.getApplication(), LinearLayoutManager.VERTICAL, false));
        adapter.setOnItemLongClickListener(this);
        adapter.setOnLoadMoreListener(this);
        adapter.setOnQrCodeClickListener(this);
    }

    @Override
    protected ILoadingType.LoadingType initLoadType() {
        return ILoadingType.LoadingType.LOADING_TYPE_COVER;
    }

    @Override
    public void showLoading(String msg) {
        if (isFirst) {
            super.showLoading(msg);
        }
    }

    @Override
    public void hideLoading() {
        if (isFirst) {
            super.hideLoading();
            isFirst = false;
        }
        reFreshLayout.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
        currentPageNo = 1;

        getNewsPersenter.getNewList(RequestBean.COLUMN_GZPT, 1);
    }


    @Override
    public void onRetry() {

        getNewsPersenter.getNewList(RequestBean.COLUMN_GZPT, currentPageNo);
    }

    @Override
    public void onLoadMore() {
        currentPageNo++;
        getNewsPersenter.getNewList(RequestBean.COLUMN_GZPT, currentPageNo);
    }

    @Override
    public void OnQrCodeClickListener(Tab7New data) {
        QRCodeDialog qrCodeDialog = new QRCodeDialog(getActivity());
        qrCodeDialog.setQrCodeName(data.getTitle());
        qrCodeDialog.setQrCodeUrl(data.getTitleUrl());
        qrCodeDialog.show();
    }

    @Override
    public boolean onItemLongClick(View v, int position) {
        downLoadImage(tab1NewList.get(position).getTitleUrl(), tab1NewList.get(position).getTitle());
        return false;
    }

    /**
     * 下载图片
     *
     * @param url url
     */
    public void downLoadImage(final String url, String fileName) {
        if (TextUtils.isEmpty(url)) {
            showToast("二维码路径有误");
            return;
        }
        if (TextUtils.isEmpty(fileName)) {
            fileName = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        }
        final String filePath = Environment.getExternalStorageDirectory() + File.separator + fileName + ".jpg";
        DownLoadService.downLoadFile(url)
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody body) throws Exception {
                        InputStream in = null;
                        FileOutputStream out = null;
                        try {

                            in = null;
                            out = null;
                            in = body.byteStream();
                            out = new FileOutputStream(filePath);
                            int c;

                            while ((c = in.read()) != -1) {
                                out.write(c);
                            }
                        } catch (IOException e) {

                        } finally {
                            if (in != null) {
                                in.close();
                            }
                            if (out != null) {
                                out.close();
                            }
                        }
                        return url;
                    }
                })
                .compose(RxLifecycleCompact.bind(this).<String>withObservable())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String value) {
                        showToast("二维码已经下载：" + filePath);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        showToast("下载二维码失败,请确定图片路径是否正确");
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
}